package com.crm.business.crm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.crm.business.admin.service.AdminService;
import com.crm.business.crm.mapper.CrmAllianceBusinessMapper;
import com.crm.business.crm.service.CrmPageService;
import com.crm.business.crm.service.ICrmAllianceBusinessBalanceService;
import com.crm.business.crm.service.ICrmAllianceBusinessService;
import com.crm.business.utils.ActionRecordUtil;
import com.crm.common.crm.constant.CrmEnum;
import com.crm.common.crm.constant.FieldEnum;
import com.crm.common.crm.entity.BO.CrmModelSaveBO;
import com.crm.common.crm.entity.BO.CrmRoiSearchBO;
import com.crm.common.crm.entity.BO.CrmUpdateInformationBO;
import com.crm.common.crm.entity.PO.CrmAllianceBusiness;
import com.crm.common.crm.entity.PO.CrmAllianceBusinessBalance;
import com.crm.common.crm.entity.VO.CrmFieldSortVO;
import com.crm.common.crm.entity.VO.CrmModelFiledVO;
import com.crm.common.ka.core.entity.BasePage;
import com.crm.business.servlet.BaseServiceImpl;
import com.crm.business.utils.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 加盟商充值表 服务实现类
 * </p>
 *
 * @author 阿伟
 * @since 2020-05-26
 */
@Service
@Slf4j
public class CrmAllianceBusinessServiceImpl extends BaseServiceImpl<CrmAllianceBusinessMapper, CrmAllianceBusiness> implements ICrmAllianceBusinessService, CrmPageService {

    @Autowired
    private ICrmAllianceBusinessBalanceService crmAllianceBusinessBalanceService;

    @Autowired
    private AdminService adminService;

    @Autowired
    private ActionRecordUtil actionRecordUtil;

    @Override
    public String[] appendSearch() {
        return new String[0];
    }

    @Override
    public void setOtherField(Map<String, Object> map) {

    }

    @Override
    public CrmEnum getLabel() {
        return null;
    }

    @Override
    public CrmAllianceBusiness queryById(Integer id) {
        return getBaseMapper().queryById(id);
    }

    @Override
    public void deleteByIds(List<Integer> ids) {
        removeByIds(ids);
    }

    /**
     * 列表查询
     * @param search
     * @return
     */
    @Override
    public BasePage<CrmAllianceBusiness> queryPageList(CrmRoiSearchBO search) {
        Integer pageStart = search.getPage() > 0 ? (search.getPage() - 1) * search.getLimit() : 0;
        search.setPageStart(pageStart);

        if(ObjectUtil.isEmpty(search.getDeptIds())){
            List<Integer> deptIdList = new ArrayList<>();
            deptIdList.addAll(adminService.queryChildDeptId(UserUtil.getUser().getDeptId()));
            deptIdList.add(UserUtil.getUser().getDeptId());
            search.setDeptIds(deptIdList);
        }

        List<CrmAllianceBusiness> crmAllianceBusinessList = getBaseMapper().queryPageList(search);
        BasePage<CrmAllianceBusiness> basePage = new BasePage<>(search.getPage(),search.getLimit(),crmAllianceBusinessList.size());
        basePage.setList(crmAllianceBusinessList);

        return basePage;
    }


    @Override
    public void addOrUpdate(CrmModelSaveBO crmModel) {
        CrmAllianceBusiness crmAllianceBusiness = BeanUtil.copyProperties(crmModel.getEntity(),CrmAllianceBusiness.class);
        if(crmAllianceBusiness.getId() != null){
            // 编辑
            CrmAllianceBusiness oldCrmAllianceBusiness = this.queryById(crmAllianceBusiness.getId());

            crmAllianceBusiness.setUpdateTime(new Date());
            crmAllianceBusiness.setUpdateUserId(UserUtil.getUserId());

            actionRecordUtil.updateRecord(BeanUtil.beanToMap(baseMapper.queryById(crmAllianceBusiness.getId())),BeanUtil.beanToMap(crmAllianceBusiness),CrmEnum.ALLIANCE_BUSINESS, String.valueOf(crmAllianceBusiness.getId()),crmAllianceBusiness.getId());

            updateById(crmAllianceBusiness);

            //旧余额信息更新
            CrmAllianceBusinessBalance oldCrmAllianceBusinessBalance = this.crmAllianceBusinessBalanceService.queryDataByDeptId(oldCrmAllianceBusiness.getDeptId(),oldCrmAllianceBusiness.getRechargeSource());
            if(ObjectUtil.isNotEmpty(oldCrmAllianceBusinessBalance)){
                oldCrmAllianceBusinessBalance.setBalance(oldCrmAllianceBusinessBalance.getBalance().subtract(oldCrmAllianceBusiness.getTopUpPrice()));
                this.crmAllianceBusinessBalanceService.updateById(oldCrmAllianceBusinessBalance);
            }

            //更新充值后：余额-旧充值+新充值
            CrmAllianceBusinessBalance crmAllianceBusinessBalance = this.crmAllianceBusinessBalanceService.queryDataByDeptId(crmAllianceBusiness.getDeptId(),crmAllianceBusiness.getRechargeSource());
            if(crmAllianceBusinessBalance == null){
                crmAllianceBusinessBalance = new CrmAllianceBusinessBalance();
                crmAllianceBusinessBalance.setDeptId(crmAllianceBusiness.getDeptId());
                crmAllianceBusinessBalance.setRechargeSource(crmAllianceBusiness.getRechargeSource());
                crmAllianceBusinessBalance.setBalance(crmAllianceBusiness.getTopUpPrice());
                this.crmAllianceBusinessBalanceService.save(crmAllianceBusinessBalance);
            }else{
                crmAllianceBusinessBalance.setBalance(crmAllianceBusinessBalance.getBalance().add(crmAllianceBusiness.getTopUpPrice()));
                this.crmAllianceBusinessBalanceService.updateById(crmAllianceBusinessBalance);
            }
//            crmAllianceBusinessBalance.setBalance(crmAllianceBusinessBalance.getBalance().subtract(oldCrmAllianceBusiness.getTopUpPrice()).add(crmAllianceBusiness.getTopUpPrice()));
//            this.crmAllianceBusinessBalanceService.updateById(crmAllianceBusinessBalance);
        }else{
            // 新增
            crmAllianceBusiness.setCreateTime(new Date());
            crmAllianceBusiness.setCreateUserId(UserUtil.getUserId());
            save(crmAllianceBusiness);

            actionRecordUtil.addRecord(crmAllianceBusiness.getId(), CrmEnum.ALLIANCE_BUSINESS, String.valueOf(crmAllianceBusiness.getId()));

            //新建充值后更新余额表信息
            CrmAllianceBusinessBalance crmAllianceBusinessBalance = this.crmAllianceBusinessBalanceService.queryDataByDeptId(crmAllianceBusiness.getDeptId(),crmAllianceBusiness.getRechargeSource());
            if(crmAllianceBusinessBalance == null){
                crmAllianceBusinessBalance = new CrmAllianceBusinessBalance();
                crmAllianceBusinessBalance.setDeptId(crmAllianceBusiness.getDeptId());
                crmAllianceBusinessBalance.setRechargeSource(crmAllianceBusiness.getRechargeSource());
                crmAllianceBusinessBalance.setBalance(crmAllianceBusiness.getTopUpPrice());
                this.crmAllianceBusinessBalanceService.save(crmAllianceBusinessBalance);
            }else{
                crmAllianceBusinessBalance.setBalance(crmAllianceBusinessBalance.getBalance().add(crmAllianceBusiness.getTopUpPrice()));
                this.crmAllianceBusinessBalanceService.updateById(crmAllianceBusinessBalance);
            }
        }
    }

    @Override
    public void updateInformation(CrmUpdateInformationBO updateInformationBO) {

    }

    /**
     * 查询所有字段
     *
     * @return data
     */
    @Override
    public List<CrmModelFiledVO> queryField(Integer id) {
        return queryDefaultField();
    }

    /**
     * 下载导入模板
     *
     * @param response 线索id
     */
    @Override
    public void downloadExcel(HttpServletResponse response) throws IOException {

    }

    public List<CrmFieldSortVO> queryListHead(){
        List<CrmFieldSortVO> list = new ArrayList<>();
        list.add(new CrmFieldSortVO().setName("投放平台").setType(FieldEnum.SELECT.getType()).setFieldName("putinPlatform").setFormType(FieldEnum.SELECT.getFormType()));
        list.add(new CrmFieldSortVO().setName("大类").setType(FieldEnum.TEXT.getType()).setFieldName("category").setFormType(FieldEnum.TEXT.getFormType()));
        list.add(new CrmFieldSortVO().setName("渠道充值金额").setType(FieldEnum.FLOATNUMBER.getType()).setFieldName("putinMoney").setFormType(FieldEnum.FLOATNUMBER.getFormType()));
        list.add(new CrmFieldSortVO().setName("渠道消耗金额").setType(FieldEnum.FLOATNUMBER.getType()).setFieldName("practicalPutinMoney").setFormType(FieldEnum.FLOATNUMBER.getFormType()));
        list.add(new CrmFieldSortVO().setName("渠道返点金额").setType(FieldEnum.FLOATNUMBER.getType()).setFieldName("putinRebatesMoney").setFormType(FieldEnum.FLOATNUMBER.getFormType()));
        list.add(new CrmFieldSortVO().setName("渠道赔付金额").setType(FieldEnum.FLOATNUMBER.getType()).setFieldName("putinCompensateMoney").setFormType(FieldEnum.FLOATNUMBER.getFormType()));
        list.add(new CrmFieldSortVO().setName("渠道转入金额").setType(FieldEnum.FLOATNUMBER.getType()).setFieldName("rollinMoney").setFormType(FieldEnum.FLOATNUMBER.getFormType()));
        list.add(new CrmFieldSortVO().setName("渠道转出金额").setType(FieldEnum.FLOATNUMBER.getType()).setFieldName("rolloutMoney").setFormType(FieldEnum.FLOATNUMBER.getFormType()));
        list.add(new CrmFieldSortVO().setName("备注").setType(FieldEnum.TEXT.getType()).setFieldName("remark").setFormType(FieldEnum.TEXT.getFormType()));
        list.add(new CrmFieldSortVO().setName("表单录入时间").setType(FieldEnum.DATE.getType()).setFieldName("putinFormDate").setFormType(FieldEnum.DATE.getFormType()));
        list.add(new CrmFieldSortVO().setName("创建时间").setType(FieldEnum.DATETIME.getType()).setFieldName("createTime").setFormType(FieldEnum.DATETIME.getFormType()));
        list.add(new CrmFieldSortVO().setName("创建人").setType(FieldEnum.TEXT.getType()).setFieldName("putinUserName").setFormType(FieldEnum.TEXT.getFormType()));
        list.add(new CrmFieldSortVO().setName("审核状态").setType(FieldEnum.TEXT.getType()).setFieldName("checkStatus").setFormType(FieldEnum.TEXT.getFormType()));

        return list;
    }

    public void exportExcel(HttpServletResponse response, CrmRoiSearchBO search){

    }

    /**
     * 查询所有字段
     *
     * @return data
     */
    @Override
    public List<CrmModelFiledVO> queryDefaultField() {
        //查询 线索 自定义字段 中 客户来源 作为 投放平台下拉选项
        List<CrmModelFiledVO> filedList = new ArrayList<>();
        //投放金额
        filedList.add(new CrmModelFiledVO("putinMoney", FieldEnum.FLOATNUMBER,"投放金额",1).setIsNull(1).setFormType(FieldEnum.FLOATNUMBER.getFormType()));
        //实际投放金额
        filedList.add(new CrmModelFiledVO("practicalPutinMoney", FieldEnum.FLOATNUMBER,"实际投放金额",1).setIsNull(1).setFormType(FieldEnum.FLOATNUMBER.getFormType()));
        //课程期数
        filedList.add(new CrmModelFiledVO("coursePeriods", FieldEnum.TEXT,"课程期数",1).setIsNull(1).setIsUnique(1).setFormType(FieldEnum.TEXT.getFormType()));
        //投放日期
        filedList.add(new CrmModelFiledVO("putinDate", FieldEnum.TEXT,"投放日期",1).setIsNull(1).setIsUnique(1).setFormType(FieldEnum.TEXT.getFormType()));
        return filedList;
    }

    public CrmAllianceBusiness getListById(Integer id){
        CrmAllianceBusiness crmAllianceBusiness= baseMapper.queryListById(id);
        String batchIds=crmAllianceBusiness.getBatchId();
        crmAllianceBusiness.setFileList(baseMapper.queryListCrmBatch(batchIds));
        return crmAllianceBusiness;
    }
}
